package org.vt.ece4564.pcw.assignment2;

import java.io.IOException;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import javax.servlet.ServletConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.vt.ece4564.pcw.assignment2data.Contact;

@SuppressWarnings("serial")
public class TextInClassPostContacts extends HttpServlet {
	
	@Override
	public void init(ServletConfig servletConfig) {
		
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws IOException {
		
		response.setContentType("text/plain");
		
		List<Cookie> cookies;
		
		if (request.getCookies() != null) {
			cookies = Arrays.asList(request.getCookies());
		} else {
			response.getWriter().println("Error: No cookies provided");
			return;
		}
		
		String username = "";
		
		for (Cookie c : cookies) {
			String name = c.getName();
			String value = c.getValue();
			
			if (name.equals("loggedIn")) {
				String[] values = value.split(":");
				Date currentDate = new Date();
				long cookieExpiration = Long.valueOf(values[1]).longValue();
				
				if (currentDate.getTime() > cookieExpiration) {
					response.getWriter().write("Error: Expired Cookie");
					return;
				}
				
				username = values[0];
				break;
			}
		}
		
		if (username.equals("")) { //Correct cookie not found
			response.getWriter().write("Error: Invalid Cookie");
			return;
		}
		
		List<String> names;
		List<String> numbers;
		
		if (request.getParameterValues("names") == null) {
			response.getWriter().write("Error: No names specified");
			return;
		}
		
		if (request.getParameterValues("numbers") == null) {
			response.getWriter().write("Error: No numbers specified");
			return;
		}
		
		names = Arrays.asList(request.getParameterValues("names"));
		numbers = Arrays.asList(request.getParameterValues("numbers"));
		
		if (names.size() != numbers.size()) {
			response.getWriter().write("Error: Number of names and numbers must match");
			return;
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		for (int i = 0; i < names.size(); i++) {
			pm.makePersistent(new Contact(username, names.get(i), numbers.get(i)));
		}
		
		response.getWriter().write("Success");
		
	}
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.sendRedirect("/postContacts.html");
	}
	
}
